package org.common.utils.generatormapper;
import org.common.utils.generatormapper.data.DataManager;
import org.common.utils.generatormapper.event.EventManager;
import org.common.utils.generatormapper.window.GeneratorMapperWindow;
import org.common.utils.tool.window.PlaceholderTool;
import org.common.utils.tool.window.ComponentTool;
import org.common.utils.tool.window.RedirectSystemPrintln;
import org.common.utils.tool.window.VersionTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.util.Map;
import java.util.ResourceBundle;

public class GeneratorMapperManager {
    private static final Logger log = LoggerFactory.getLogger(GeneratorMapperManager.class);

    private static final GeneratorMapperManager INSTANCE = new GeneratorMapperManager();

    private Map<Class<?> , Map<String , Component>> componentMap;

    private DataManager dataManager = new DataManager();

    private GeneratorMapperWindow window;

    private EventManager eventManager = new EventManager();

    private GeneratorMapperManager() {

    }

    public static GeneratorMapperManager getInstance() {
        return INSTANCE;
    }

    public void initBefore(GeneratorMapperWindow window) {
        this.window = window;
        this.eventManager.initBefore();
        this.dataManager.initBefore();
    }

    public void initAfter(GeneratorMapperWindow window) {
        this.componentMap = ComponentTool.getComponents(window);
        PlaceholderTool.register(getComponent(JTextField.class, "txtHost") , getString("GeneratorEntityWindow.txtMysqlHost.example.text"));
        PlaceholderTool.register(getComponent(JTextField.class, "txtGeneratorPath") , getString("GeneratorEntityWindow.txtJavaDir.example.text"));
        PlaceholderTool.register(getComponent(JTextField.class, "txtGeneratorPackage") , getString("GeneratorEntityWindow.txtPackageName.example.text"));

        VersionTool.initVersionTitle(window , getString("GeneratorEntityWindow.this.title"));
        RedirectSystemPrintln.redirect(getComponent(JTextArea.class, "txtAreaLog"));
    }

    public GeneratorMapperWindow getWindow() {
        return window;
    }

    public String getString(String key) {
        return ResourceBundle.getBundle("localization").getString(key);
    }

    /**
     * 根据指定类型和名称，获取组件对象
     * @param clzss 组件类型
     * @param name 组件名称
     * @return 返回对应的组件对象
     * @param <T> 接收泛型
     */
    public <T extends Component> T getComponent(Class<T> clzss , String name) {
        Map<String, Component> classMap = componentMap.get(clzss);
        if(classMap == null)
            return null;
        return (T)classMap.get(name);
    }

    public DataManager getDataManager() {
        return dataManager;
    }
}
